package com.yonyou.cyxdms.sysAuth.service.service.broker;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.framework.util.http.RestHttpUtil;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.BrokerNameEnum;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.EmpInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.broker.*;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerDetailDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.DealerInfoPO;
import com.yonyou.cyxdms.sysAuth.service.entity.EmpPo;
import com.yonyou.cyxdms.sysAuth.service.entity.EmployeePO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.feign.CustomerService;
import com.yonyou.cyxdms.sysAuth.service.feign.FileServiceClient;
import com.yonyou.cyxdms.sysAuth.service.mapper.DealerInfoMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.EmpMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.EmployeeMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.vo.user.BrokerDealerInfoVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.Poster;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 经纪人表 服务实现类
 *
 * @author zhangsx
 * @since 2018-09-15z
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BrokerServiceImpl implements BrokerService {

    @Resource
    EmpMapper empMapper;
    @Autowired
    BaseCommonRegionService baseCommonRegionService;

    @Resource
    UserMapper userMapper;

    @Resource
    EmployeeMapper employeeMapper;
    @Resource
    DealerInfoMapper dealerInfoMapper;

    @Autowired
    CustomerService customerService;

    @Autowired
    UserLoginService userLoginService;

    @Autowired
    SystemParamService systemParamService;
    @Autowired
    RedisClient redisClient;

    @Autowired
    RestTemplate restTemplate;

    @Qualifier(value = "restTemplateNoLb")
    @Autowired
    RestTemplate restTemplateNoLb;

    @Autowired
    private FileServiceClient fileServiceClient;


    private Logger logger = LoggerFactory.getLogger(BrokerServiceImpl.class);

    /**
     * //获取个人名片的信息详情
     *
     * @author Administrato
     * @since 2018/12/4
     */
    @Transactional(readOnly = true)
    @Override
    public BrokerCardDTO getBrokerCard(Long uid) {
        //获取名片信息
        BrokerVO brokerVO = userMapper.getBrokerCard(uid);
        // 获取登录信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        brokerVO.setDealerId(Long.parseLong(loginInfoDto.getOwnerId()));
        logger.debug("名片查询结果：{}", JSON.toJSONString(brokerVO));
        //用po获取所需数据
        String appId = brokerVO.getAppId();
        String avatar = brokerVO.getAvatar();
        String name = brokerVO.getName();
//        Integer type = Integer.parseInt(StringUtils.isBlank(brokerVO.getBrokerType()) ? "1" : brokerVO.getBrokerType());
        String phone = brokerVO.getPhone();
        String weChat = brokerVO.getWeChat();
        //po里面获取dealerId字段
        Long dealerId = brokerVO.getDealerId();
        String dealerContactAddress = null;
        String dealerShortName = null;
        String dealerName = null;
        Float longitude = null;
        Float latitude = null;
        //通过获取dealer微服务里面的dealer_id找到经销商信息
        DealerDetailDTO dealerDetailDTO = new DealerDetailDTO();
        dealerDetailDTO.setDealerId(dealerId);
        DealerInfoDTO exDealerInfoDTO = dealerInfoMapper.dealerDetailInfo(dealerDetailDTO);
        if (exDealerInfoDTO != null) {
            logger.debug("从dealer服务中获取经销商信息结果：{}", exDealerInfoDTO);
            //得到经销商地址
            dealerContactAddress = exDealerInfoDTO.getDealerContactAddress();
            dealerShortName = exDealerInfoDTO.getDealerShortName();
            dealerName = exDealerInfoDTO.getDealerName();
            longitude = StringUtils.isNullOrEmpty(exDealerInfoDTO.getLongitude()) ? null : Float.valueOf(exDealerInfoDTO.getLongitude());
            latitude = StringUtils.isNullOrEmpty(exDealerInfoDTO.getLatitude()) ? null : Float.valueOf(exDealerInfoDTO.getLatitude());
        }
        // 创建map集合把数据放回到集合中
        BrokerCardDTO cardDTO = new BrokerCardDTO();
        cardDTO.setDealerContactAddress(dealerContactAddress);
        cardDTO.setDealerShortName(dealerShortName);
        cardDTO.setDealerName(dealerName);
        cardDTO.setLatitude(latitude);
        cardDTO.setLongitude(longitude);
        cardDTO.setName(name);
        cardDTO.setPhone(phone);
        // fixme 名片中后台提供死的职位数据：销售顾问
        cardDTO.setBrokerRuleCode(String.valueOf(BrokerNameEnum.SalesCounsultant.getKey()));
        cardDTO.setBrokerRule(BrokerNameEnum.SalesCounsultant.getValue());

        cardDTO.setAvatar(avatar);
        cardDTO.setWeChat(weChat);
        cardDTO.setDealerId(dealerId);
        cardDTO.setApppId(appId);

        //返回map值
        return cardDTO;
    }

    /**
     * 获取顾问信息
     *
     * @param userTokens
     * @return com.yonyou.cyx.broker.service.model.dto.broker.BrokerDTO
     * @author zhangsx
     * @since 2019/1/9
     */
    @Override
    public List<BrokerInfoDTO> getBrokerByUserTokens(List<String> userTokens) {
        logger.debug("批量获取顾问信息开始，获取的 uids：{}", userTokens);
        List<BrokerDTO> list = userMapper.getBrokersByUids(userTokens);
        // todo 居新改的bug
        if (!list.isEmpty()) {
            logger.debug("list:{}", list.get(0));
        }
        List<BrokerInfoDTO> infoDTOList = new ArrayList<>();
        for (BrokerDTO brokerDTO : list) {
            BrokerInfoDTO dto = BeanMapperUtil.copyProperties(brokerDTO, BrokerInfoDTO.class);
//            dto.setTypeName(BrokerNameEnum.getByKey(dto.getType()).getValue());
            infoDTOList.add(dto);
        }
        return infoDTOList;
    }


    @Override
    public List<BrokerInfoDTO> getBrokerByUidsAndAppId(List<String> userTokens, String appId) {
        logger.debug("批量获取顾问信息开始，获取的 uids：{}", userTokens);
        List<BrokerDTO> list = userMapper.getBrokersByUids(userTokens);
        List<BrokerInfoDTO> infoDTOList = new ArrayList<>();
        if (list.size() == 0) {
            return infoDTOList;
        }
        for (BrokerDTO brokerDTO : list) {
            BrokerInfoDTO dto = BeanMapperUtil.copyProperties(brokerDTO, BrokerInfoDTO.class);
//            dto.setTypeName(BrokerNameEnum.getByKey(dto.getType()).getValue());
            infoDTOList.add(dto);
        }
        return infoDTOList;
    }

    /**
     * 模糊查询经纪人信息
     *
     * @author dengqiang
     * @since 2019/2/19
     */
    @Override
    public List<BrokerCardVo> queryBrokerInfo(String appId, String forWord) {
        List<String> userIds = new ArrayList<>();
        userIds.add(forWord);

        List<BrokerCardVo> brokerInfo = getBrokerInfo(appId, userIds, null);

        return brokerInfo;
    }

    /**
     * 根据经销商id查询所有顾问人员信息
     *
     * @param dealerId
     * @return
     */
    @Override
    public List<BrokerByDlerIdDTO> queryBrokerInfoByDealerId(String dealerId) {
        List<BrokerByDlerIdDTO> list = userMapper.selectUserListByDealerId(dealerId);
        return CommonUtils.isNullOrEmpty(list) ? new ArrayList<>() : list;
    }

    @Override
    public List<BrokerByDlerIdDTO> queryBrokerInfoByDealerCodeAndAppId(String dealerCode, String appId) {
        List<BrokerByDlerIdDTO> list = userMapper.selectUserListByDealerCode(dealerCode);
        return CommonUtils.isNullOrEmpty(list) ? new ArrayList<>() : list;
    }

    /**
     * 根据DMS系统的ID获取经纪人信息
     *
     * @param dmsId dmsId
     * @return com.yonyou.cyx.broker.service.model.dto.BrokerDTO
     * @author renwd
     * @since 2018/9/19
     */
    @Override
    @Transactional(readOnly = true)
    public BrokerDTO getByDmsId(String dmsId) {
        // 获取登录信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        UserPO userpo = userMapper.selectByAppUserId(loginInfoDto.getAppId(), Long.parseLong(dmsId));
        EmployeePO employeepo = employeeMapper.selectById(loginInfoDto.getEmployeeId());
        EmpPo empPo = empMapper.selectById(employeepo.getEmpId());

        LambdaQueryWrapper<DealerInfoPO> query = new QueryWrapper<DealerInfoPO>().lambda();
        query.eq(DealerInfoPO::getDealerCode, employeepo.getOwnerCode());
        query.eq(DealerInfoPO::getAppId, employeepo.getAppId());
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectOne(query);

        BrokerDTO brokerDTO = new BrokerDTO();
        brokerDTO.setAdress(empPo.getAddress());
        brokerDTO.setAppId(employeepo.getAppId());

        Date birthday = empPo.getBirthday();
        if (birthday == null) {
            brokerDTO.setBirthday(null);
        } else {
            LocalDate date = LocalDate.of(birthday.getYear(), birthday.getMonth(), birthday.getDay());
            LocalTime time = LocalTime.of(0, 0, 0);
            LocalDateTime localDateTime = LocalDateTime.of(date, time);

            brokerDTO.setBirthday(localDateTime);
        }

        brokerDTO.setUid(Long.parseLong(String.valueOf(userpo.getUserId())));
        // brokerDTO.setDealerCode(userPO.getOwnerCode());
        brokerDTO.setDealerId(Long.parseLong(String.valueOf(dealerinfopo.getDealerId())));
        brokerDTO.setDmsId(String.valueOf(userpo.getUserId()));
        brokerDTO.setZipcode(empPo.getZipCode());
        brokerDTO.setUserCode(userpo.getUserCode());
        brokerDTO.setEmail(empPo.geteMail());
        brokerDTO.setGender(empPo.getGender());
        brokerDTO.setIdCard(empPo.getCertificateId());
        brokerDTO.setAvatar(empPo.getHeadPortrait());

        return brokerDTO;
    }

    /**
     * 根据IM系统的userCode 和 AppId
     * 获取经纪人信息
     *
     * @param userCode userCode
     * @param appId    appId
     * @return
     * @author czb
     * @since 2019/09/09
     */
    @Override
    @Transactional(readOnly = true)
    public BrokerDTO getByUserCodeAndAppId(String userCode, String appId) {
        // 获取登录信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        UserPO userpo = userMapper.selectByAppUserCode(loginInfoDto.getAppId(), loginInfoDto.getUserCode());
        EmpPo empPo = empMapper.selectById(userpo.getEmpId());

        LambdaQueryWrapper<DealerInfoPO> query = new QueryWrapper<DealerInfoPO>().lambda();
        query.eq(DealerInfoPO::getCompanyId, userpo.getCompanyId());
        query.eq(DealerInfoPO::getAppId, empPo.getAppId());
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectOne(query);

        BrokerDTO brokerDTO = new BrokerDTO();
        brokerDTO.setAdress(empPo.getAddress());
        brokerDTO.setAppId(empPo.getAppId());

        Date birthday = empPo.getBirthday();
        if (birthday == null) {
            brokerDTO.setBirthday(null);
        } else {
            LocalDate date = LocalDate.of(birthday.getYear(), birthday.getMonth(), birthday.getDay());
            LocalTime time = LocalTime.of(0, 0, 0);
            LocalDateTime localDateTime = LocalDateTime.of(date, time);

            brokerDTO.setBirthday(localDateTime);
        }

        brokerDTO.setUid(Long.parseLong(String.valueOf(userpo.getUserId())));
        //brokerDTO.setDealerCode(userPO.getOwnerCode());
        brokerDTO.setDealerId(Long.parseLong(String.valueOf(dealerinfopo.getDealerId())));
        brokerDTO.setDmsId(String.valueOf(userpo.getUserId()));
        brokerDTO.setZipcode(empPo.getZipCode());
        brokerDTO.setUserCode(userpo.getUserCode());
        brokerDTO.setEmail(empPo.geteMail());
        brokerDTO.setGender(empPo.getGender());
        brokerDTO.setIdCard(empPo.getCertificateId());
        brokerDTO.setAvatar(empPo.getHeadPortrait());

        return brokerDTO;
    }

    /**
     * H5获取销售顾问信息
     *
     * @param brokerId 销售顾问id
     * @return java.util.Map
     * @author Zhangsx
     * @date 2018年9月6日
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> findBrokerInfo(Long brokerId) {
        logger.debug("获取销售顾问信息开始");
        // 获取登录信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return userMapper.findBrokerInfo(brokerId, loginInfoDto.getAppId());
    }

    public RestTemplate getRestTemplate(String url) {
        return RestHttpUtil.isService(url) ? restTemplate : restTemplateNoLb;
    }

    /**
     * 获取顾问信息
     *
     * @author lijun
     */
    @Override
    public List<BrokerCardVo> getBrokerInfo(String appId, List<String> userIds, List<String> userCodes) {
        String url = systemParamService.getParamValueByCode("getBrokerInfo", appId);

        if (!StringUtils.isBlank(url)) {
            String response = RestHttpUtil.get(getRestTemplate(url), url + "?appId={1}&userIds={2}", String.class, appId, String.join(",", userIds));
            RestResultResponse<List<BrokerCardVo>> result = JSONUtil.jsonToObj(response, new TypeReference<RestResultResponse<List<BrokerCardVo>>>() {
            });

            if (result.getResultCode() >= 200 && result.getResultCode() <= 206) {
                return result.getData();
            } else {
                throw new ServiceBizException(result.getErrMsg());
            }
        }

        List<BrokerCardVo> list = userMapper.getBrokerInfo(appId, userIds, userCodes);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        } else {
            LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
            logger.debug("原有的loginInfoDTO：{}", loginInfoDto);
            loginInfoDto.setAppId(appId);
            StringBuilder dealerFullAddress = new StringBuilder();
            try {
                if (list.size() == 1) {
                    BrokerCardVo brokerInfo = list.get(0);
                    if (!StringUtils.isNullOrEmpty(brokerInfo.getProvinceId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(brokerInfo.getProvinceId());
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                    if (!StringUtils.isNullOrEmpty(brokerInfo.getCityId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(brokerInfo.getCityId());
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                    if (!StringUtils.isNullOrEmpty(brokerInfo.getCountyId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(brokerInfo.getCountyId());
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                }
                logger.debug("补充省市信息：{}", dealerFullAddress.toString());
            } catch (Exception e) {
                logger.error("经销商地址获取失败！", e);
                throw new ServiceBizException("经销商地址获取失败！");
            }
            list.stream().forEach(r -> {
                r.setBrokerRuleCode(String.valueOf(BrokerNameEnum.SalesCounsultant.getKey()));
                String str = (dealerFullAddress.length() == 0 ? "" : dealerFullAddress.toString()) + (r.getDealerContactAddress() == null ? "" : r.getDealerContactAddress());
                r.setDriveAddress(str);
                r.setDealerContactAddress(str);
            });
            return list;
        }
    }

    /**
     * 传播APP中获取展示顾问信息
     *
     * @author houkh
     */
    @SneakyThrows
    @Override
    public BrokerDealerInfoVO brokerInfo(String userId, String appId) {
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.debug("loginInfotDTO:{}", login);
        if (login.getUserId() == null) {
            logger.debug("登陆信息中没有userId，从参数中取");
            if (StringUtils.isNullOrEmpty(userId)) {
                logger.error("登陆信息、入参中均无userId");
                throw new ServiceBizException("无用户ID");
            } else {
                login.setUserId(Long.valueOf(userId));
                if (login.getAppId() == null) {
                    login.setAppId(appId);
                }
            }
        } else {
            userId = String.valueOf(login.getUserId());
        }
        logger.debug("loginInfotDTO:{}", login);
        EmpInfoDTO empInfoDTO = null;
        String empUrl = systemParamService.getParamValueByCode(CommonConstants.EMP_INFO, login.getAppId());
        if (StringUtils.isNullOrEmpty(empUrl)) {
            empInfoDTO = userLoginService.empInfo();
            logger.debug("数据库中查询到的用户信息：{}", empInfoDTO);
        } else {
            String messageFormat = MessageFormat.format(BaseDataCommonConstants.SUB_JWT, appId, userId);
            Object jwt = redisClient.get(messageFormat);
            logger.debug("缓存中取得子系统缓存的jwt：key-->{},userId-->{},value-->{}", messageFormat, userId, JSONUtil.objectToJson(jwt));
            Map map = new HashMap();
            map.put("appId", appId);
            map.put("userId", userId);
            if (jwt != null) {
                map.put("jwt", jwt);
            }
            //兼容广汽蔚来
            Map query = new HashMap();
            query.put("appId", appId);
            query.put("userId", userId);

            logger.debug("从远端获取用户信息请求参数列表：{}", JSONUtil.objectToJson(map));
            HttpHeaders httpHeaders = RestHttpUtil.getHeader(map);
            String response = RestHttpUtil.get(httpHeaders, getRestTemplate(empUrl), RestHttpUtil.getUrl(empUrl, query), null, String.class);

            logger.debug("调用远端接口的结果：{}", response);
            //TODO JSON解析
            RestResultResponse<EmpInfoDTO> res = JSONUtil.jsonToObj(response, new TypeReference<RestResultResponse<EmpInfoDTO>>() {
            });
            EmpInfoDTO data = res.getData();
            BrokerDealerInfoVO result = new BrokerDealerInfoVO();
            BeanUtils.copyProperties(data, result);
            if (result.getAppId() == null) {
                result.setAppId(appId);
            }
            if (result.getUserId() == null) {
                result.setUserId(userId);
            }
            // fixme 这里涉及到IM注册ID
            result.setUserToken(result.getUserId());
            if (result.getDealerCode() == null) {
                result.setDealerCode(login.getOwnerCode());
            }
            if (result.getDealerId() == null) {
                result.setDealerId(login.getOwnerId());
            }
            if (result.getBrokerRule() == null) {
                result.setBrokerRule(data.getRoleName());
            }
            result.setHeadImg(data.getHeadPortrait());
            if (data.getNickName() != null) {
                result.setWeChat(data.getNickName());
            }
            return result;
        }

        if (empInfoDTO == null) {
            throw new ServiceBizException("未获取到信息！");
        }

        BrokerDealerInfoVO brokerInfo = new BrokerDealerInfoVO();
        BeanUtils.copyProperties(empInfoDTO, brokerInfo);
        brokerInfo.setUserId(login.getUserId().toString());
        brokerInfo.setDealerCode(login.getOwnerCode());
        brokerInfo.setDealerId(login.getOwnerId());
        brokerInfo.setBrokerRule(empInfoDTO.getRoleName());
        brokerInfo.setHeadImg(empInfoDTO.getHeadPortrait());//头像
        brokerInfo.setWeChat(empInfoDTO.getNickName()); //微信
        brokerInfo.setName(brokerInfo.getUserName());
        brokerInfo.setDriveAddress(brokerInfo.getAddress());
        Poster poster1 = new Poster();
        String qrCodeUrl = "https://bjev-cms-oss-public.oss-cn-beijing.aliyuncs.com/20201103/b3a7547ca08542898611e4923b14cafb.png"; //二维码
        poster1.setWidth(612);
        poster1.setHeight(490);
        poster1.setName(org.apache.commons.lang3.StringUtils.isNotBlank(brokerInfo.getUserName()) && brokerInfo.getUserName().length()>6? brokerInfo.getUserName().substring(0,6)+"..." : brokerInfo.getUserName());
        poster1.setDealerName(brokerInfo.getDealerName());
        poster1.setDesc(brokerInfo.getAddress());
        poster1.setPhone(brokerInfo.getPhone());
        poster1.setBrokerRule(brokerInfo.getBrokerRule());
        poster1.setQrCodeUrl(qrCodeUrl); //二维码
        if(brokerInfo.getHeadImg()!=null){
            poster1.setGoodsUrl(brokerInfo.getHeadImg()); //顶部banner
        }else{
            poster1.setGoodsUrl("https://bjev-cms-oss-public.oss-cn-beijing.aliyuncs.com/20201102/146d7b2ed86543aa9c2608d2beea16f8.png"); //顶部banner
        }

        Poster poster = PosterUtil.initPoster(poster1);
        BufferedImage canvas=PosterUtil.drawPoster(poster);

        String fileName ="upload"+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+".png";
        File resultImg = new File("opt/",fileName);
        if(!resultImg.exists()) {
            // 先创建文件所在的目录
            logger.info("wfz-----------生成opt文件夹开始");
            resultImg.getParentFile().mkdirs();
            logger.info("wfz-----------生成opt文件夹结束");
            try {
                // 创建新文件
                ImageIO.write(canvas, "png", resultImg);

                //上传服务器代码
                //ByteArrayOutputStream bs = new ByteArrayOutputStream();
                //ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
                //ImageIO.write(canvas, "png", imgOut);
                //InputStream inSteam = new ByteArrayInputStream(bs.toByteArray());
                //String url = OSSFactory.build().upload(inSteam, UUID.randomUUID().toString()+".png");
                System.out.println("生成成功！");
                System.out.println("生成文件路径: " + resultImg.getAbsolutePath());

                InputStream inputStream = new FileInputStream(resultImg);
                MultipartFile multipartFile = new MockMultipartFile("file",
                        resultImg.getName(), "text/plain", IOUtils.toByteArray(inputStream));
                logger.info("wfz-----------生成multipartFile文件成功");
                String url = fileServiceClient.upload(multipartFile).getData();
                logger.info("wfz-----------文件上传成功");
                brokerInfo.setBrokerRuleUrl(url);
                resultImg.delete();
                logger.info("wfz-----------文件删除成功");
            } catch (IOException e) {
                System.out.println("创建新文件时出现了错误。。。");
                e.printStackTrace();
            }
        }
        logger.debug("最终返回结果：{}", brokerInfo);
        return brokerInfo;
    }
    /**
     * 传播APP中获取展示顾问信息
     *
     * @author houkh
     */
    @SneakyThrows
    @Override
    public BrokerDealerInfoVO brokerInfoApp(String userId, String appId) {
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.debug("loginInfotDTO:{}", login);
        if (login.getUserId() == null) {
            logger.debug("登陆信息中没有userId，从参数中取");
            if (StringUtils.isNullOrEmpty(userId)) {
                logger.error("登陆信息、入参中均无userId");
                throw new ServiceBizException("无用户ID");
            } else {
                login.setUserId(Long.valueOf(userId));
                if (login.getAppId() == null) {
                    login.setAppId(appId);
                }
            }
        } else {
            userId = String.valueOf(login.getUserId());
        }
        logger.debug("loginInfotDTO:{}", login);
        EmpInfoDTO empInfoDTO = null;
        String empUrl = systemParamService.getParamValueByCode(CommonConstants.EMP_INFO, login.getAppId());
        if (StringUtils.isNullOrEmpty(empUrl)) {
            empInfoDTO = userLoginService.empInfo();
            logger.debug("数据库中查询到的用户信息：{}", empInfoDTO);
        } else {
            String messageFormat = MessageFormat.format(BaseDataCommonConstants.SUB_JWT, appId, userId);
            Object jwt = redisClient.get(messageFormat);
            logger.debug("缓存中取得子系统缓存的jwt：key-->{},userId-->{},value-->{}", messageFormat, userId, JSONUtil.objectToJson(jwt));
            Map map = new HashMap();
            map.put("appId", appId);
            map.put("userId", userId);
            if (jwt != null) {
                map.put("jwt", jwt);
            }
            //兼容广汽蔚来
            Map query = new HashMap();
            query.put("appId", appId);
            query.put("userId", userId);

            logger.debug("从远端获取用户信息请求参数列表：{}", JSONUtil.objectToJson(map));
            HttpHeaders httpHeaders = RestHttpUtil.getHeader(map);
            String response = RestHttpUtil.get(httpHeaders, getRestTemplate(empUrl), RestHttpUtil.getUrl(empUrl, query), null, String.class);

            logger.debug("调用远端接口的结果：{}", response);
            //TODO JSON解析
            RestResultResponse<EmpInfoDTO> res = JSONUtil.jsonToObj(response, new TypeReference<RestResultResponse<EmpInfoDTO>>() {
            });
            EmpInfoDTO data = res.getData();
            BrokerDealerInfoVO result = new BrokerDealerInfoVO();
            BeanUtils.copyProperties(data, result);
            if (result.getAppId() == null) {
                result.setAppId(appId);
            }
            if (result.getUserId() == null) {
                result.setUserId(userId);
            }
            // fixme 这里涉及到IM注册ID
            result.setUserToken(result.getUserId());
            if (result.getDealerCode() == null) {
                result.setDealerCode(login.getOwnerCode());
            }
            if (result.getDealerId() == null) {
                result.setDealerId(login.getOwnerId());
            }
            if (result.getBrokerRule() == null) {
                result.setBrokerRule(data.getRoleName());
            }
            result.setHeadImg(data.getHeadPortrait());
            if (data.getNickName() != null) {
                result.setWeChat(data.getNickName());
            }
            return result;
        }

        if (empInfoDTO == null) {
            throw new ServiceBizException("未获取到信息！");
        }
        BrokerDealerInfoVO brokerInfo = new BrokerDealerInfoVO();
        BeanUtils.copyProperties(empInfoDTO, brokerInfo);
        brokerInfo.setUserId(login.getUserId().toString());
        brokerInfo.setDealerCode(login.getOwnerCode());
        brokerInfo.setDealerId(login.getOwnerId());
        brokerInfo.setBrokerRule(empInfoDTO.getRoleName());
        brokerInfo.setHeadImg(empInfoDTO.getHeadPortrait());//头像
        brokerInfo.setWeChat(empInfoDTO.getNickName()); //微信
        brokerInfo.setName(brokerInfo.getUserName());
        brokerInfo.setDriveAddress(brokerInfo.getAddress());
        Poster poster1 = new Poster();
        String qrCodeUrl = "sysmanage-service/src/main/java/com/yonyou/cyxdms/sysAuth/service/service/broker/pic/aaa.png"; //二维码
        poster1.setWidth(604);
        poster1.setHeight(402);
        poster1.setName(brokerInfo.getUserName());
        poster1.setDealerName(brokerInfo.getDealerName());
        poster1.setDesc(brokerInfo.getAddress());
        poster1.setPhone(brokerInfo.getPhone());
        poster1.setBrokerRule(brokerInfo.getBrokerRule());
        poster1.setQrCodeUrl(qrCodeUrl); //二维码
        if(brokerInfo.getHeadImg()!=null){
            poster1.setGoodsUrl(brokerInfo.getHeadImg()); //顶部banner
        }else{
            poster1.setGoodsUrl("sysmanage-service/src/main/java/com/yonyou/cyxdms/sysAuth/service/service/broker/pic/nohead.png"); //顶部banner
        }

        Poster poster = PosterUtil.initPoster(poster1);
        BufferedImage canvas=PosterUtil.drawPoster(poster);

        String fileName ="upload"+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+".png";
        File resultImg = new File("opt/",fileName);
        if(!resultImg.exists()) {
            // 先创建文件所在的目录
            logger.info("wfz-----------生成opt文件夹开始");
            resultImg.getParentFile().mkdirs();
            logger.info("wfz-----------生成opt文件夹结束");
            try {
            // 创建新文件
                ImageIO.write(canvas, "png", resultImg);

                //上传服务器代码
                //ByteArrayOutputStream bs = new ByteArrayOutputStream();
                //ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
                //ImageIO.write(canvas, "png", imgOut);
                //InputStream inSteam = new ByteArrayInputStream(bs.toByteArray());
                //String url = OSSFactory.build().upload(inSteam, UUID.randomUUID().toString()+".png");
                System.out.println("生成成功！");
                System.out.println("生成文件路径: " + resultImg.getAbsolutePath());

                InputStream inputStream = new FileInputStream(resultImg);
                MultipartFile multipartFile = new MockMultipartFile("file",
                        resultImg.getName(), "text/plain", IOUtils.toByteArray(inputStream));
                logger.info("wfz-----------生成multipartFile文件成功");
                String url = fileServiceClient.upload(multipartFile).getData();
                logger.info("wfz-----------文件上传成功");
                brokerInfo.setBrokerRuleUrl(url);
                resultImg.delete();
                logger.info("wfz-----------文件删除成功");
            } catch (IOException e) {
                System.out.println("创建新文件时出现了错误。。。");
                e.printStackTrace();
            }
        }
        logger.debug("最终返回结果：{}", brokerInfo);
        return brokerInfo;
    }

}



